import { getTodayTime } from '../../../utils/dateformat';

// 任务线程，用于调度， 目前还没想好如何实现，暂时作为执行层（无调度效果）
class CrawlerThread {
  lazyTime: number;
  callBackFn: ()=>void;
  morningTime: {
    start: number,
    end: number
  };
  afternoonTime: {
    start: number,
    end: number
  };;
  workDay: Array<number>;
  constructor(options) {

    // 默认60秒
    this.lazyTime = 60 * 1000;

    // callBackFn
    this.callBackFn = null;

    // 上午时间
    this.morningTime = {
      start: 9.5 * 60 * 60 * 1000,
      end: 11.5 * 60 * 60 * 1000
    }

    // 下午时间
    this.afternoonTime = {
      start: 13 * 60 * 60 * 1000,
      end: 15 * 60 * 60 * 1000
    }

    // 工作日
    this.workDay = [1, 2, 3, 4, 5];

    this._init(options);
  }

  _init(options) {
    const {
      lazyTime,
      callBackFn,
    } = options;
    this.lazyTime = lazyTime ? lazyTime : this.lazyTime;
    this.callBackFn = callBackFn instanceof Function ? callBackFn : null;
  }

  startThread() {
    if (this.callBackFn === null) {
      throw new Error('必须传入爬取的逻辑');
    };

    // 今天0点时间戳
    const todayTime = getTodayTime();

    // 今天时间
    const now = new Date();

    // 今天周几
    const day = now.getDay();
    if (!this.workDay.includes(day)) {
      console.log('今天周末，休息！');
      return;
    }
    
    // 目前时间戳
    const nowTime = now.getTime();

    const isMorningTime = this.morningTime.start + todayTime < nowTime && nowTime < this.morningTime.end + todayTime;
    const isAfternoonTime = this.morningTime.start + todayTime < nowTime && nowTime < this.morningTime.end + todayTime;

    if (!isMorningTime && !isAfternoonTime) {
      console.log('非工作时间，休息！');
      return;
    }

    this.callBackFn();
  }

  getLazyTime() {
    return this.lazyTime;
  }
};

export default CrawlerThread;